/* gcc trd.c -l pthread
 * */
#include <pthread.h>
#include <stdio.h>
#include <windows.h>
/*
#include <unistd.h>
#include <pthread.h>
*/
#define MAX 11
pthread_t thread[3];
pthread_mutex_t mut;
int k = 1;
int *a;

void thread1(void* arg){
	int num = *(int*)arg;
	for(; k<MAX; k){
		pthread_mutex_lock(&mut);
		if( k<MAX ) printf("thread %d: k = %-2d\t\tthread id: %lu\n", num, k++, pthread_self());
		pthread_mutex_unlock(&mut);
		Sleep(1000);
		//sleep(1);
	}
	printf("thread %d end\n", num);
	pthread_exit(arg);
}

void thread_create(int len){
	int temp, i=0;
	memset(&thread, 0, sizeof(thread));
	for(;i<len;i++){
		if((temp = pthread_create(&thread[i], NULL, (void *)thread1, (void*)a+(i)*sizeof(int))) != 0){
			printf("create thread %d failed\n", i);
		}
	}
}

void thread_wait(int len){
	int i=0;
	char* ret;
	for(;i<len;){
		if( pthread_join(thread[i], (void**)&ret) == 0 ){
			//printf("%d\n", *(int*)ret);
			//printf("thread %d done\n", i);
			printf("thread %d done\n", *(int*)ret);
			i++;
		}
	}
}

int* init(int *a, int len){
	int i=0;
	/*
	if(len>200){
		printf("Open too many threads...\n");
		exit(0);
	}
	*/
	for(; i<len; i++){
		//a[i] = i+1;
		*(a+i) = i+1;
	}
	return a;
}
int main(int argc, char** argv){
	printf("Run in %s, %d\n", __FILE__, __LINE__);
	int len = argc==1 ? 2 : atoi(argv[1]);
	a = (int *)calloc(len, sizeof(int));
	a = init(a, len);
	pthread_mutex_init(&mut, NULL);
	printf("Prc createing threads...\n");
	thread_create(len);
	printf("Prc waiting for threads done...\n");
	thread_wait(len);
	pthread_mutex_destroy(&mut);
	free(a);
	return 0;
}
